package com.hertz.alarm.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.hertz.alarm.dao.EhCacheDao;
import com.hertz.alarm.entity.IrisNbaAlarm;
import com.hertz.alarm.entity.MatchNba;
import com.hertz.alarm.service.EntityService;
import com.hertz.alarm.service.IrisNbaAlarmService;
import com.hertz.alarm.service.IrisUserService;
import com.hertz.alarm.service.MatchNbaService;
import com.hertz.alarm.util.Constants4Ehcache;
import com.hertz.alarm.util.ConstantsType;
import com.hertz.alarm.util.DateUtils;
@Service
public class IrisNbaAlarmServiceImpl extends BaseServiceImpl implements IrisNbaAlarmService {
	private Logger logger = LoggerFactory.getLogger(IrisNbaAlarmServiceImpl.class);
	
	@Resource
	private MatchNbaService matchNbaService;
	@Resource
	private EntityService entityService;
	@Resource
	private IrisUserService irisUserService;
	@Resource
	private EhCacheDao ehcacheDao;
	@Override
	public boolean save(IrisNbaAlarm irisNbaAlarm){
		logger.debug("save irisNbaAlarm:{}",irisNbaAlarm.toString());
		IrisNbaAlarm r = entityService.save(irisNbaAlarm);
		
		if(r == null || r.getId() == null || r.getId() <= 0 ){
			return false;
		}else{
			save2Cache(irisNbaAlarm);
			return true;
		}
	}
	
	@Override
	public boolean update(IrisNbaAlarm fromDB,IrisNbaAlarm irisNbaAlarm){
		logger.debug("update irisNbaAlarm:{}",irisNbaAlarm.toString());
		fromDB.setAgain(irisNbaAlarm.getAgain());
		fromDB.setIncrease(irisNbaAlarm.getIncrease());
		fromDB.setPeriod(irisNbaAlarm.getPeriod());
		fromDB.setRemain(irisNbaAlarm.getRemain());
		fromDB.setRingName(irisNbaAlarm.getRingName());
		fromDB.setScoreDiff(irisNbaAlarm.getScoreDiff());
		fromDB.setWave(irisNbaAlarm.getWave());
		fromDB.setVolume(irisNbaAlarm.getVolume());
		entityService.update(irisNbaAlarm);
		save2Cache(irisNbaAlarm);
		return true;
	}

	@Override
	public IrisNbaAlarm getById(long id) {
		IrisNbaAlarm irisNbaAlarm = (IrisNbaAlarm)ehcacheDao.get(String.format(Constants4Ehcache.KEY_MATCH_ALARM_ID, id), Constants4Ehcache.REGION_MATCH_ALARM);
		if(irisNbaAlarm == null){
			irisNbaAlarm = entityService.getById(id, IrisNbaAlarm.class);
			if(irisNbaAlarm != null){
				save2Cache(irisNbaAlarm);
			}
		}
			
		return irisNbaAlarm;
	}

	@Override
	public List<IrisNbaAlarm> listBy(long uid,String ymd){
		
		List<Long> list = (ArrayList<Long>)ehcacheDao.get(String.format(Constants4Ehcache.KEY_MATCH_ALARM_UID_YMD, uid,ymd), Constants4Ehcache.REGION_MATCH_ALARM);
		List<IrisNbaAlarm> irisNbaAlarms = new ArrayList<IrisNbaAlarm>();
		if(list == null || list.size() == 0){
			List<MatchNba> matchs = matchNbaService.listByYmd(ymd);
			if(matchs == null || matchs.size() == 0){
				return Collections.emptyList();
			}else{
				for (MatchNba matchNba : matchs) {
					IrisNbaAlarm irisNbaAlarm = getBy(uid, matchNba.getId());
					if(irisNbaAlarm != null && irisNbaAlarm.getStatus() == ConstantsType.ALARM_STATUS.un_alarm.getValue()){
						irisNbaAlarms.add(irisNbaAlarm);
					}
				}
			}
		}else{
			for(Long id : list){
				irisNbaAlarms.add(getById(id));
			}
		}
		return irisNbaAlarms;
	}
	
	@Override
	public List<IrisNbaAlarm> listAllFromMtimeFromDb(String ymd) {
		long time = DateUtils.string2Time(ymd, DateUtils.Y_M_D);
		return baseDAO.listAll(IrisNbaAlarm.GET_ALL_FROM_MTIME, time);
	}

	@Override
	public IrisNbaAlarm getBy(long uid,long mid){
		Long id = (Long)ehcacheDao.get(String.format(Constants4Ehcache.KEY_MATCH_ALARM_UID_MID, uid,mid), Constants4Ehcache.REGION_MATCH_ALARM);
		if(id == null || id == 0){
			IrisNbaAlarm alarm = baseDAO.getUniqueResult(IrisNbaAlarm.GET_BY_UID_MID, uid,mid);
			if(alarm != null)
				save2Cache(alarm);
			return alarm;
		}else{
			return getById(id);
		}
	}

//	@Override
//	public List<MatchNba> isAlarm(String token) {
//		if(StringUtils.isBlank(token)){
//			logger.error("uid error,token:{}",token);
//			return null;
//		}
//		IrisUser user = irisUserService.getByToken(token);
//		if(user == null){
//			logger.error("no user ,token:{}",token);
//			return null;
//		}
//		return this.isAlarm(user);
//	}
//
//	@Override
//	public List<MatchNba> isAlarm(IrisUser irisUser) {
//		if(irisUser == null){
//			logger.error("irisUser param is null");
//			return null;
//		}
//		String ymd = DateUtils.today(DateUtils.Y_M_D);
//		List<IrisNbaAlarm> list = this.listBy(irisUser.getId(), ymd);
//		if(list == null){
//			logger.debug("no alarm today");
//			return null;
//		}
//		List<MatchNba> result = new ArrayList<MatchNba>();
//		for(IrisNbaAlarm item : list){
//			MatchNba match = matchNbaService.getById(item.getMid());
//			if(match != null && match.getPeriod() > ConstantsType.MATCH_PERIOD.UN_PLAY.getValue()){//开赛
//				if (match.getPeriod() == item.getPeriod()
//						|| match.getPeriod() >= ConstantsType.MATCH_PERIOD.OVERTIME
//								.getValue()
//						&& item.getPeriod() == ConstantsType.MATCH_PERIOD.OVERTIME
//								.getValue()) {//节数
//					if (match.getRemain().compareTo(String.valueOf(item.getRemain())) <= 0
//							&& item.getScoreDiff() <= Math.abs(match
//									.getHostScore() - match.getGuestScore())) {//单节剩余时间 与 分差
//						result.add(match);
//					}
//				}
//			}
//		}
//		return result;
//	}

	@Override
	@Deprecated
	public List<IrisNbaAlarm> getsById(String aids) {
		if(StringUtils.isBlank(aids)){
			logger.error("aids is blank");
			return null;
		}
		String[] aidArr = aids.split(",");
		List<IrisNbaAlarm> result = new ArrayList<IrisNbaAlarm>();
		for(String aid:aidArr){
			if(!StringUtils.isNumeric(aid)){
				logger.error("aid is not number,aid:{}",aid);
				result.add(null);
			}else{
				IrisNbaAlarm temp = entityService.getById(Long.valueOf(aid), IrisNbaAlarm.class);
				result.add(temp);
			}
		}
		return result;
	}

	@Override
	public boolean isAlarm(long mid,IrisNbaAlarm irisNbaAlarm) {
		MatchNba matchNba = matchNbaService.getById(mid);
		return matchNba == null ? false : isALarm(matchNba,irisNbaAlarm);
	}

	@Override
	public boolean isALarm(IrisNbaAlarm irisNbaAlarm) {
		if(irisNbaAlarm == null)
			return false;
		return isAlarm(irisNbaAlarm.getMid(),irisNbaAlarm);
	}

	@Override
	public boolean isALarm(MatchNba matchNba,IrisNbaAlarm irisNbaAlarm) {
		boolean result = false;
		if(matchNba == null){
			return result;
		}
		if(irisNbaAlarm == null){
			return result;
		}
		
		if(irisNbaAlarm.getStatus() < ConstantsType.ALARM_STATUS.un_alarm.getValue()){
			return result;
		}
		// every period notice
		if(irisNbaAlarm.getEveryQuarter() && irisNbaAlarm.getNoticePeriod() != ConstantsType.MATCH_PERIOD.END.getValue()){
			if(matchNba.getPeriod() == ConstantsType.MATCH_PERIOD.END.getValue()){//match end notice
				irisNbaAlarm.setNoticePeriod(ConstantsType.MATCH_PERIOD.END.getValue());
				irisNbaAlarm.setStatus(ConstantsType.ALARM_STATUS.end_alarm.getValue());
				save(irisNbaAlarm);
				result = true;
				return result;
			}else if(matchNba.getRemain().equals("0") && matchNba.getPeriod() > irisNbaAlarm.getNoticePeriod()){
				irisNbaAlarm.setNoticePeriod(matchNba.getPeriod());
				save(irisNbaAlarm);
				result = true;
			}
		}
		if(matchNba.getPeriod() == ConstantsType.MATCH_PERIOD.END.getValue()){//match end notice
			irisNbaAlarm.setNoticePeriod(ConstantsType.MATCH_PERIOD.END.getValue());
			irisNbaAlarm.setStatus(ConstantsType.ALARM_STATUS.end_alarm.getValue());
			save(irisNbaAlarm);
			result = true;
			return result;
		}else if (irisNbaAlarm.getPeriod() != 0 && matchNba.getPeriod() == irisNbaAlarm.getPeriod() && Integer.valueOf(matchNba.getRemain().split("：")[0]) < irisNbaAlarm.getRemain()){//节数
			irisNbaAlarm.setStatus(ConstantsType.ALARM_STATUS.end_alarm.getValue());
			save(irisNbaAlarm);
			result = true;
			return result;
		}else{
			return result;
		}
	}

//	@Override
//	public MatchNba isAlarm(IrisUser irisUser, IrisNbaAlarm irisNbaAlarm) {
//		if(irisUser == null){
//			logger.error("irisUser param is null");
//			return null;
//		}
//		if(irisNbaAlarm == null){
//			logger.error("no irisNbaAlarm");
//			return null;
//		}
//		if(irisNbaAlarm.getUid() != irisUser.getId()){
//			logger.error("no permission");
//			return null;
//		}
//		MatchNba match = matchNbaService.getById(irisNbaAlarm.getMid());
//		if(match == null){
//			logger.error("match is null");
//			return null;
//		}
//		if(match.getMatchDay().compareTo(DateUtils.today(DateUtils.Y_M_D)) < 0 ){
//			logger.error("alarm expire");
//			irisNbaAlarm.setStatus(ConstantsType.ALARM_STATUS.admin_cancel.getValue());
//			save(irisNbaAlarm);
//			return null;
//		}
//		boolean isReturn = false;
//		if(match != null && match.getPeriod() > ConstantsType.MATCH_PERIOD.UN_PLAY.getValue()){//开赛
//			if (match.getPeriod() == irisNbaAlarm.getPeriod()
//					|| (match.getPeriod() >= ConstantsType.MATCH_PERIOD.OVERTIME.getValue()
//					&& irisNbaAlarm.getPeriod() == ConstantsType.MATCH_PERIOD.OVERTIME.getValue())) {//节数
//				if (Integer.valueOf(match.getRemain().split("：")[0]) <= irisNbaAlarm.getRemain()){
//					if(irisNbaAlarm.getScoreDiff() < 0 || irisNbaAlarm.getScoreDiff() >= Math.abs(match.getHostScore() - match.getGuestScore())){
//						irisNbaAlarm.setStatus(ConstantsType.ALARM_STATUS.do_alarm.getValue());
//						save(irisNbaAlarm);
//						isReturn = true;
//					}else{
//						irisNbaAlarm.setStatus(ConstantsType.ALARM_STATUS.no_alarm.getValue());
//						save(irisNbaAlarm);
//					}
//				}
//			}
//		}
//		return isReturn ? match : null;
//	}
	
	private void save2Cache(IrisNbaAlarm irisNbaAlarm){
		ehcacheDao.update(String.format(Constants4Ehcache.KEY_MATCH_ALARM_ID, irisNbaAlarm.getId()), irisNbaAlarm, Constants4Ehcache.REGION_MATCH_ALARM);
		ehcacheDao.save(String.format(Constants4Ehcache.KEY_MATCH_ALARM_UID_MID, irisNbaAlarm.getUid(),irisNbaAlarm.getMid()), irisNbaAlarm.getId(), Constants4Ehcache.REGION_MATCH_ALARM);
		List<Long> list = (ArrayList<Long>)ehcacheDao.get(String.format(Constants4Ehcache.KEY_MATCH_ALARM_UID_YMD, irisNbaAlarm.getUid(),DateUtils.timeFormat(irisNbaAlarm.getMatchTime(),DateUtils.Y_M_D)), Constants4Ehcache.REGION_MATCH_ALARM);
		if(list == null){
			list = new ArrayList<Long>();
		}
		if(!list.contains(irisNbaAlarm.getId()))
			list.add(irisNbaAlarm.getId());
		ehcacheDao.update(String.format(Constants4Ehcache.KEY_MATCH_ALARM_UID_YMD, irisNbaAlarm.getUid(),DateUtils.timeFormat(irisNbaAlarm.getMatchTime(),DateUtils.Y_M_D)),list, Constants4Ehcache.REGION_MATCH_ALARM);
	}
	
	public void cancel(long aid){
		IrisNbaAlarm irisNbaAlarm = getById(aid);
		entityService.delete(aid, IrisNbaAlarm.class);
		ehcacheDao.remove(String.format(Constants4Ehcache.KEY_MATCH_ALARM_ID, aid), Constants4Ehcache.REGION_MATCH_ALARM);
		if(irisNbaAlarm != null){
			ehcacheDao.remove(String.format(Constants4Ehcache.KEY_MATCH_ALARM_UID_MID, irisNbaAlarm.getUid(),irisNbaAlarm.getMid()),Constants4Ehcache.REGION_MATCH_ALARM);
		}
		List<Long> list = (ArrayList<Long>)ehcacheDao.get(String.format(Constants4Ehcache.KEY_MATCH_ALARM_UID_YMD, irisNbaAlarm.getUid(),DateUtils.timeFormat(irisNbaAlarm.getMatchTime(),DateUtils.Y_M_D)), Constants4Ehcache.REGION_MATCH_ALARM);
		if(list == null){
			list = new ArrayList<Long>();
		}else{
			list.remove(aid);
		}
		ehcacheDao.update(String.format(Constants4Ehcache.KEY_MATCH_ALARM_UID_YMD, irisNbaAlarm.getUid(),DateUtils.timeFormat(irisNbaAlarm.getMatchTime(),DateUtils.Y_M_D)),list, Constants4Ehcache.REGION_MATCH_ALARM);
		
	}
}
